package com.zhongzhi.javafx.controller;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;

import com.zhongzhi.common.Common;
import com.zhongzhi.common.Plc;

import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventDispatcher;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Paint;
import javafx.stage.Modality;
import javafx.stage.Stage;

public class PLCController implements Initializable{
	@FXML
	private AnchorPane AP;
	@FXML
	private Label NAME;
	@FXML
	private Label IP;
	@FXML
	private Label PORT;
	@FXML
	private Label STATE;
    @FXML
    private Button open;
	
	private Timer timer;
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		// TODO Auto-generated method stub
		Parent parent = AP.getParent();
		Plc plc =Common.getPlc();
		open.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				// TODO Auto-generated method stub
				Parent root;
				try {
					root = FXMLLoader.load(getClass().getResource("/fxml/function/OpenRun.fxml"));
					Scene scene = new Scene(root);
					Stage stage = new Stage();
					stage.setScene(scene);
					stage.setTitle("运行");
					stage.getIcons().add(new Image("/Images/tb.png"));
					stage.setResizable(false);//窗口不可改变大小
					stage.initModality(Modality.APPLICATION_MODAL);//窗口模态
					stage.show();//窗口出现
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
		if (timer==null) {
			timer = new Timer();
			timer.scheduleAtFixedRate(new TimerTask() {
				@Override
				public void run() {
					Platform.runLater(new Runnable() {
						@Override
						public void run() {
							NAME.setText(plc.getPlcName());
							IP.setText("IP地址: "+plc.getHost());
							PORT.setText("端口: "+plc.getPort().toString());
							SetTextColour(STATE, plc.getPlcState(), "连接中", "已断开", "未连接");
						}
					});
				}
			} , 100, 500);
			Common.getTimelist().add(timer);
		}
	}

	private void SetTextColour(Label label,Boolean bool,String run,String stop,String open) {
		
		if (bool==null) {
			label.setText(open);
			label.setTextFill(Paint.valueOf("#000000"));
		}else if (bool==true) {
			label.setText(run);
			label.setTextFill(Paint.valueOf("#00cf00"));
		}else{
			label.setText(stop);
			label.setTextFill(Paint.valueOf("#cf0000"));
		}
	}
	
}
